package com.app.utils;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import com.app.Application;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by Administrator on 2017/5/3.
 */

public class ImageUtil {

    private static final String LOG_TAG = ImageUtil.class.getSimpleName();
    // 打开相册请求码
    public static final int REQUEST_CODE_GALLERY = 100;
    // 打开相机请求码
    public static final int REQUEST_CODE_CAMERA = 101;
    // 裁剪结果请求码
    public static final int REQUEST_CODE_CROP = 102;

    public static String tempFileName = "tempImage.jpeg";

    private static File mTempFile;

    public static String cropFileName = "cropTempImage.jpeg";

    public static File cropTempFile;

    public static final int IMAGE_WIDTH = 600;

    public static final int IMAGE_HEIGHT = 600;


    /**
     * 初始化截图文件
     */
    public static void initTempFile() {
        mTempFile = new File(FileUtils.getTempCacheDir(), tempFileName);

    }

    /**
     * 获取截图文件
     *
     * @return
     */
    public static File getTempFile() {
        return mTempFile;
    }


    /**
     * 获取裁剪之后的文件
     *
     * @return
     */
    public static File getCropFile() {
        return cropTempFile;
    }


    private static void copyStream(InputStream input, OutputStream output) throws IOException {
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = input.read(buffer)) != -1) {
            output.write(buffer, 0, bytesRead);
        }
    }

    /**
     * 打开相册并回调
     */
    public static void openGallery(Activity activity) {
        if (null == activity) {
            return;
        }
        PackageManager pm = activity.getPackageManager();
        initTempFile();
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        if (photoPickerIntent.resolveActivity(pm) != null) {
            activity.startActivityForResult(photoPickerIntent, REQUEST_CODE_GALLERY);
        }
    }


    /**
     * 相册图片uri转换成文件缓存在本地
     */
    public static void galleryResultToFile(Activity activity, Uri uri, ImageListener listener) {
        try {
            if (null != activity && null != uri) {
                InputStream inputStream = activity.getContentResolver().openInputStream(uri);
                initTempFile();
                FileOutputStream fileOutputStream = new FileOutputStream(getTempFile());
                copyStream(inputStream, fileOutputStream);
                fileOutputStream.close();
                inputStream.close();
                listener.onSelectSucceed(getTempFile());
            } else {
                ToastUtil.getInstance().showToast(Application.instance, "该照片格式有误,请重选", Toast.LENGTH_LONG);
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, "Error while creating temp file", e);
            if (null != listener) {
                listener.onSelectFailed();
            }
        }
    }


    /**
     * 打开系统裁剪图片工具
     * @param activity
     * @param uri
     */
    public static void cropImage(Activity activity,  Uri uri) {
        if (activity == null) {
            return;
        }
        if (uri == null) {
            ToastUtil.getInstance().showToast(activity, "图片处理错误");
            return;
        }
        cropTempFile = new File(FileUtils.getTempCacheDir(), cropFileName);
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 3);
        intent.putExtra("aspectY", 3);
        intent.putExtra("outputX", IMAGE_WIDTH);
        intent.putExtra("outputY", IMAGE_HEIGHT);
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cropTempFile));
        activity.startActivityForResult(intent, REQUEST_CODE_CROP);
    }

    /**
     * 打开相机
     *
     * @param activity
     */
    public static void openCamera(Activity activity) {
        Intent intentFromCapture = new Intent(
                MediaStore.ACTION_IMAGE_CAPTURE);
        // 判断存储卡是否可以用，可用进行存储
        String state = Environment
                .getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            String path = FileUtils.getTempCacheDir() + "/";
            File dirFile = new File(path);
            if (!dirFile.exists()) {
                dirFile.mkdir();
            }
            mTempFile = new File(path + tempFileName);
            intentFromCapture.putExtra(
                    MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(mTempFile));
        }

        activity.startActivityForResult(intentFromCapture,
                REQUEST_CODE_CAMERA);
    }




    public interface ImageListener {
        void onSelectSucceed(File file);
        void onSelectFailed();
        void onCropSucceed(File file);
        void onCropFailed();
    }

}
